Working With Toast Notification in Windows Phone 7


Introduction

In this article we are going to see how to use the Toast Notification in windows phone 7. Windows Phone 7 application development supports push notification which provides developers a much more convenient option to transfer message Windows Phone 7 device from a web service when ever a new event occurs. Push notifications are of 3 types as follows

  • Toast Notification - This notification is launched at the top of the screen with the custom message such as an email alert or weather alert. The notification will be displayed for 10 second unless and until the user will dismiss the alert. If the user clicks on the alert then the application which sends the notification will be launched
  • Tile Notification - This notification is used to display dynamic representation of the application state, we can control the image, text and badge count of the notification.
  • Raw Notification - This notification is used only when the application is running on the foreground and if the application services are running background the notification will not be delivered and it gets discarded which is not delivered to the windows phone device.

We will see in depth on each notification and see a demo application for each notification one by one in our upcoming articles. Let us see the step by step process on how to create a TOAST application, we need to create a client application to send the notification to the device which we will be covering in this article.

Steps

Open Visual Studio 2010 in administrator mode and create a new Silverlight for Windows Phone 7 application with a valid project name as shown in the screen below.

img1.gif

Now add a button to create the push channel which will be required to create a Toast notification, if there are any already available notification events available it will use the same else it will create a new notification event and then connects through the channel. Add the below XAML code to get the channel notification to trigger.

XAML Code

<Grid x:Name="LayoutRoot" Background="Transparent">

    <Grid.RowDefinitions>

        <RowDefinition Height="Auto"/>

        <RowDefinition Height="*"/>

    </Grid.RowDefinitions>

 

    <!--TitlePanel contains the name of the application and page title-->

    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

        <TextBlock x:Name="ApplicationTitle" Text="F5DEBUG WP7 TUTORIALS" Style="{StaticResource PhoneTextNormalStyle}"/>

        <TextBlock x:Name="PageTitle" Text="Toast Notification" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

    </StackPanel>

 

    <!--ContentPanel - place additional content here-->

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

        <Button Content="Establish Channel!!!" Height="149" HorizontalAlignment="Left" Margin="73,88,0,0" Name="button1" VerticalAlignment="Top" Width="299" Click="button1_Click" />

    </Grid>

</Grid>

 

Now we need to go to the code behind and start the process of establishing the Notification channel to get the events trigger. To do that first let we need to add the below two using statements.

C# Code

using Microsoft.Phone.Notification;

using System.Diagnostics;

 

Now we need to write the code to get the open channel details which will be used to send the Toast Notification, to do that we will use the output window to get the channel details. Copy the below code to the code behind page.

C# Code

</pre>

private void getChannelURI(Uri value)

 {

 Dispatcher.BeginInvoke(() =>

 {

 Debug.WriteLine("URI: " + value.ToString());

 });

 

Debug.WriteLine("URI: " + value.ToString());

 }

<pre>

 

Now we need to handle the BindToShellToast of HttpNotificationChannel to bind the toast notifications to do that add the below code.

</pre>

private static void ShellBinding(HttpNotificationChannel httpChannel)

 {

 try

 {

 httpChannel.BindToShellToast();

 }

 catch (Exception)

 {

 //Catach if required.

 }

 }

<pre>

 

Now we need to add the below code to check if the application is running correctly and get the toast notification message in order to log it for administrating purpose.

C# Code

void Channel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)

 {

 Dispatcher.BeginInvoke(() =>

 {

 Debug.WriteLine("Toast Notification Received!!!");

 if (e.Collection != null)

 {

 Dictionary collection = (Dictionary)e.Collection;

 System.Text.StringBuilder messageBuilder = new System.Text.StringBuilder();

 }

 });

 }

void ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)

 {

 getChannelURI(e.ChannelUri);

 }

 

Now we need to have a method which will do the channel setup step by step, first it will check if the channel is already available if its available we need to check the channel is null if null then we need to close the channel and open a new channel. But initially if the channel is not available then we can directly create the HttpNotificationChannel and do the process to create the channel as shown in the screen below.

C# Code

private void ChannelSetup()

 {

 HttpNotificationChannel httpChn = null;

 string chnName = "Channel0";

 

httpChn = HttpNotificationChannel.Find(chnName);

 

if (httpChn != null)

 {

 if (httpChn.ChannelUri == null)

 {

 httpChn.UnbindToShellToast();

 httpChn.Close();

 ChannelSetup();

 return;

 }

 else

 {

 getChannelURI(httpChn.ChannelUri);

 }

 ShellBinding(httpChn);

 }

 else

 {

 httpChn = new HttpNotificationChannel(chnName);

 httpChn.ChannelUriUpdated += new EventHandler(ChannelUriUpdated);

 httpChn.ShellToastNotificationReceived += new EventHandler(Channel_ShellToastNotificationReceived);

 httpChn.Open();

 ShellBinding(httpChn);

 }

 }

 

Now we need to call the above method on the button click event as shown in the screen below.

C# Code

private void button1_Click(object sender, RoutedEventArgs e)

 {

 ChannelSetup();

 }

 

Now we are done with the Windows phone 7 client notification application, we will check by building and executing the application and we can see the Windows Phone 7 Emulator as shown in the screen below.

img2.gif

Now click on the Establish Channel button which will establish the channel if not already created else will use existing channel and we can see the channel URI in the Output window since we have coded to get the channel details. To get the output window just go to the Visual Studio tool bar and select View –> Output window and we can see the output window as shown in the screen below.

img3.gif

Now copy and keep the channel details on to a separate notepad, Now we need to create a Server to post the toast notifications to the application device to show the toast.

We will create a web page from which we will post the toast notifications and get the notification on to the Windows Phone 7 device. To start with first create a ASP.NET Web application in C# as shown in the screen below.

img8.gif

Now add the below design code to the ASPX page so that we will get the same look and feel for this tutorial, here we have added 3 labels and 3 textboxes to get the user inputs (Channel URI and notification message) and a button to trigger the event for the toast message to be sent to the Windows Phone 7 Device .

ASPX Code

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"

    CodeBehind="Default.aspx.cs" Inherits="F5debugWp7ToastNotificationServer._Default" %>

 

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

    <style type="text/css">

        .style1

        {

            width: 100%;

        }

        .style2

        {

        }

        .style3

        {

            width: 690px;

        }

        .style4

        {

            width: 143px;

        }

        .style5

        {

            width: 38px;

        }

    </style>

</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

    <table>

        <tr>

            <td colspan="3">

                <asp:Label ID="Label1" runat="server" Font-Bold="true" Font-Size="Large" Text="F5Debug Windows Phone 7 Toast Notification"></asp:Label>

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;

            </td>

            <td>

                <asp:Label ID="Label2" runat="server" Text="Channel URI"></asp:Label>

            </td>

            <td>

                <asp:TextBox ID="TextBox1" runat="server" Width="661px"></asp:TextBox>

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;

            </td>

            <td>

                <asp:Label ID="Label3" runat="server" Text="Notification Title"></asp:Label>

            </td>

            <td>

                <asp:TextBox ID="TextBox2" runat="server" Width="661px"></asp:TextBox>

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;

            </td>

            <td>

                <asp:Label ID="Label4" runat="server" Text="Notification SubTitle"></asp:Label>

            </td>

            <td>

                <asp:TextBox ID="TextBox3" runat="server" Width="659px"></asp:TextBox>

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

        <tr>

            <td>

                &nbsp;

            </td>

            <td>

                <asp:Button ID="Button1" runat="server" Font-Bold="True" OnClick="Button1_Click"

                    Text="Send Notification" Width="134px" />

            </td>

            <td>

                <asp:Label ID="lblresult" runat="server"></asp:Label>

            </td>

            <td>

                &nbsp;

            </td>

        </tr>

    </table>

</asp:Content>

 

img5.gif

Now go to the code behind and add the below code, this code will get the user inputs mainly the Channel URI and pass the message to the Microsoft Push Notification services. Just copy the below code to proceed further.

Code Behind

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net;

using System.IO;

using System.Text;

 

namespace F5debugWp7ToastNotificationServer

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

        }

        protected void Button1_Click(object sender, EventArgs e)

        {

            string PushNotificationXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<wp:Notification xmlns:wp=\"WPNotification\">" + "<wp:Toast>" + "<wp:Text1>{0}</wp:Text1>" + "<wp:Text2>{1}</wp:Text2>" + "</wp:Toast>" + "</wp:Notification>";

            string strChannelURI = TextBox1.Text.ToString();

            string strNotifitcationTitle = TextBox2.Text.ToString();

            string strNotifitcationsubTitle = TextBox3.Text.ToString();

            if (strChannelURI == string.Empty || strNotifitcationTitle == string.Empty || strNotifitcationsubTitle == string.Empty)

            {

                lblresult.Text = "All the fields are Mandatory!!!";

                return;

            }

            HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(strChannelURI);

            sendNotificationRequest.Method = "POST";

            sendNotificationRequest.Headers = new WebHeaderCollection();

            sendNotificationRequest.ContentType = "text/xml";

            sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");

            sendNotificationRequest.Headers.Add("X-NotificationClass", "2");

            string str = string.Format(PushNotificationXML, strNotifitcationTitle, strNotifitcationsubTitle);

            byte[] strBytes = new UTF8Encoding().GetBytes(str);

            sendNotificationRequest.ContentLength = strBytes.Length;

            using (Stream requestStream = sendNotificationRequest.GetRequestStream())

            {

                requestStream.Write(strBytes, 0, strBytes.Length);

            }

            HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse();

            string notificationStatus = response.Headers["X-NotificationStatus"];

            string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];

 

            lblresult.Text = "Status: " + notificationStatus + " : " + deviceConnectionStatus;

        }

    }

}

 

Now run the Windows Phone 7 Toast notification application to get the channel URI, once we got the channel URI keep the application running in background and navigate to the home page of the Windows Phone 7 Application. Now run the Server application (F5debugWp7ToastNotificationServer) and enter the details as shown in the screen below.

img6.gif

Now click on the Send Notification button and navigate to the Windows Phone 7 Emulator to see the Toast Notification Message on the top as shown in the screen below.

img7.gif

Conclusion

So in this article we have seen what Push Notification is in Windows Phone 7 and the types of notification available. Also we have seen how to create a Toast Notification step by step in detail.


Similar Articles